﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using Commons.Web;
using MvcMasterPage.Helper;
using MvcMasterPage.BLL;
using MvcMasterPage.Entity;

namespace MvcMasterPage.Controllers
{
    public class CommonController : BaseController
    {
        ReviewManager reviewManager;
        UserManager userManager;
        public CommonController()
        {
            reviewManager = new ReviewManager();
            userManager = new UserManager();
        }
        /// <summary>
        /// 文件上传jquery.uploadify
        /// </summary>
        /// <returns></returns>
        public ActionResult Upload()
        {
            Response.ContentType = "text/plain";
            Response.Charset = "utf-8";
            var file = Request.Files["Filedata"];
            string uploadPath = Server.MapPath(Request.Form["folder"]) + "\\";

            if (file != null)
            {
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                file.SaveAs(uploadPath + file.FileName);
                //下面这句代码缺少的话，上传成功后上传队列的显示不会自动消失
                Response.Write("1");
            }
            else
            {
                Response.Write("0");
            }
            return View();
        }

        #region 公用评论模块
        /// <summary>
        /// 评论公用视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Review(int? objID, int? objType)
        {
            return View(new Review
            {
                ObjID = objID ?? 0,
                ObjType = objType ?? 1,
                Info = ""
            });
        }
        [RoleFilter(RoleFlag.User), HttpPost]
        public JsonResult Review(Review entity)
        {
            JsonResult js = new JsonResult();
            string _code = Session["ValidateCode"].ToString().ToLower();
            js.Data = new
            {
                res = true,
                info = "操作成功",
                href = "location.href",
            };

            if (Request.Form["VCode"].ToLower() != _code)
            {
                js.Data = new
                {
                    res = false,
                    info = "验证码错误！",
                    url = ""
                };
            }
            else
            {
                entity.CreateDate = DateTime.Now;
                entity.UserID = UserID;
                VM = reviewManager.AddReview(entity);
                if (!VM.IsComplete)
                    js.Data = new
                    {
                        res = false,
                        info = "操作失败，信息为：" + VM.GetMessage(),
                        href = "",
                    };
            }
            return js;
        }

        /// <summary>
        /// 异步评论视图
        /// </summary>
        /// <param name="objID"></param>
        /// <param name="objType"></param>
        /// <returns></returns>
        public ActionResult AJAXReview(int? objID, int? objType)
        {
            return View(new Review
            {
                ObjID = objID ?? 0,
                ObjType = objType ?? 1,
            });
        }
        [HttpPost]
        public JsonResult AJAXReview(Review entity)
        {
            JsonResult js = new JsonResult();
            js.Data = new { res = true };
            if (ModelState.IsValid)
            {
                //相关逻辑
            }
            else
            {
                js.Data = new { res = false, info = "请认真填写表单！" };
            }
            return js;
        }
        #endregion

        #region 模板页公用Action
        public ActionResult PartialHistory()
        {
            return PartialView();
        }
        public ActionResult PartialLogon()
        {
            return PartialView();//会将页面的Layout自动设为null
        }
        [HttpPost]
        public JsonResult PartialLogon(User entity)
        {
            JsonResult js = new JsonResult();

            //  entity = userManager.GetUser().Where(i => i.Name == entity.Name).FirstOrDefault();
            entity = new User { ID = 1, Name = "zzl" };
            if (entity != null)
            {
                VCommons.Http.CookieHelper.Write("eee114", "UserID", entity.ID.ToString(), 512);

                js.Data = new
                {
                    res = true,
                    info = "登陆成功" + entity.Name,
                    href = Url.Action("Index", "Home")
                };
            }
            else
            {
                js.Data = new
                {
                    res = true,
                    info = "登陆失败",
                };
            }
            return js;
        }

        public JsonResult PartialLogOut()
        {
            VCommons.Http.CookieHelper.Remove("eee114");
            return Json(new
            {
                res = true,
                info = "成功登出",
                href = Url.Action("Index", "Home")
            });
        }

        public ActionResult PartialNews()
        {
            return PartialView();
        }
        #endregion

        /// <summary>
        /// 生成验证码图像对象
        /// </summary>
        /// <returns></returns>
        public ActionResult GetValidateCode()
        {
            string code = ValidateCode.MakeVerifyCode(4);
            Session["ValidateCode"] = code;
            byte[] bytes = ValidateCode.CreatePicCode(code);
            return File(bytes, @"image/jpeg");
        }

        #region 不同的角色，有不同的action权限实例
        [RoleFilter(RoleFlag.User)]
        public ActionResult UserAction()
        {
            return View();
        }
        [RoleFilter(RoleFlag.WorkShopTeacher)]
        public ActionResult WorkShopTeacherAction()
        {
            return View();
        }
        [RoleFilter(RoleFlag.WorkShopUser)]
        public ActionResult WorkShopUserAction()
        {
            return View();
        }

        #endregion

        /// <summary>
        /// 跨域ＡＰＩ
        /// </summary>
        /// <returns></returns>
        public JsonpResult GetUserAPI(string userID)
        {
            JsonpResult result = new JsonpResult()
            {
                Data = new { name = "zzl", res = true, },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            //  throw new Exception("OK");
            return result;//反回一个callback(msg)对象

        }
    }
}
